
from django.db import transaction
from rest_framework import status
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView

from py_web.common.auth.MyAuth import MyAuth
from py_web.common.constant.SecurityConstant import START
from py_web.common.db.BaseModelViewSet import BaseModelViewSet
from py_web.security.SecuritySerialization import RoleSerializer, RoleMenuSerializer
from py_web.security.models import RoleMenu, Role
from py_web.user.Filter import RoleFilter
from py_web.user.views.views import roleMenuTreeselect, SaveOrUpdateRole

from utils.Page import MyPageNumberPagination
from utils.StrUtil import isNotEmpty

# 角色表
class RoleView(MyAuth, BaseModelViewSet):
    queryset = Role.objects.all().order_by('roleSort')
    serializer_class = RoleSerializer
    # 分页
    pagination_class = MyPageNumberPagination
    # 过滤器
    filterset_class = RoleFilter


# 查询角色列表
class ListAllRoleView(MyAuth, APIView):

    def get(self, request: Request, *args, **kwargs) -> Response:
        roleList = Role.objects.filter(status=START)
        serializer = RoleSerializer(instance=roleList, many=True)

        return Response(serializer.data)


# 修改/新增角色、菜单回显
class SelectRoleById(MyAuth, APIView):
    def get(self, request, pk):

        role = Role.objects.get(roleId=pk)
        serializer = RoleSerializer(instance=role).data

        # 菜单取树结构
        trees = roleMenuTreeselect()

        # 取权限对应id 是当前用户的权限和菜单对照的id
        roleMenu = RoleMenu.objects.filter(roleId=pk)
        s2 = RoleMenuSerializer(roleMenu, many=True).data

        serializer['menus'] = trees

        if s2:
            checkedKeys = []
            for s in s2:
                checkedKeys.append(s['menuId'])
            serializer['checkedKeys'] = checkedKeys

        return Response(serializer, status=status.HTTP_200_OK)

# 删除角色和角色选择的菜单信息
class DeleteRoleByIds(MyAuth, APIView):
    @transaction.atomic
    def delete(self, request):
        roleIds: list = request.data

        if isNotEmpty(roleIds):
            Role.objects.filter(roleId__in=roleIds).delete()
            # 删除菜单表关联关系
            RoleMenu.objects.filter(roleId__in=roleIds).delete()

        return Response(status=status.HTTP_200_OK)


# 修改角色状态
class ChangeStatusById(MyAuth, APIView):
    @transaction.atomic
    def put(self, request: Request, *args, **kwargs) -> Response:
        id = request.data['id']
        statu = request.data['status']

        if id is not None:
            roleSerializer = RoleSerializer(Role.objects.get(roleId=id), data={'roleId': id, 'status': statu})
            roleSerializer.is_valid(raise_exception=True)
            roleSerializer.save()

            return Response(status=status.HTTP_200_OK)

        return Response("请传入id编号", status=status.HTTP_400_BAD_REQUEST)


# 修改角色
class UpdateRole(MyAuth, APIView):
    @transaction.atomic
    def put(self, request: Request, *args, **kwargs) -> Response:
        # 删除角色对应菜单的数据
        RoleMenu.objects.filter(roleId=request.data['roleId']).delete()

        # 更新角色
        return SaveOrUpdateRole(request, "U")